package com.fsc.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fsc._enum.ReturnEnum;
import com.fsc.entity.ResultWrapper;
import com.fsc.entity.domain.GroupInfo;
import com.fsc.entity.domain.GroupMember;
import com.fsc.entity.dto.AddGroupDTO;
import com.fsc.entity.dto.CreateGroupDTO;
import com.fsc.entity.vo.GroupListContactVO;
import com.fsc.entity.vo.GroupWaitAddListVO;
import com.fsc.entity.vo.PersonContactListVO;
import com.fsc.entity.vo.PersonWaitAddListVO;
import com.fsc.service.GroupInfoService;
import com.fsc.service.GroupMemberService;
import com.fsc.util.OssUtil;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 群聊通讯录
 */
@RestController
@RequestMapping("/group-contacts/")
public class GroupContactController {
    @Autowired
    private GroupMemberService  groupMemberService;
    @Autowired
    private GroupInfoService groupInfoService;

    @Resource
    private RedisTemplate<String, byte[]> redisByteTemplate;

    /**
     * 创建群聊
     * @param createGroupDTO 创建群聊信息
     * @return String
     */
    @PostMapping("create")
    public ResultWrapper<String> create(@RequestBody CreateGroupDTO createGroupDTO) throws IOException {
        Integer id= StpUtil.getLoginIdAsInt();
        String groupName=createGroupDTO.getGroupName();
        if(groupInfoService.query().eq("group_name",groupName).eq("owner_id",id).exists()){
            return ResultWrapper.fail(ReturnEnum.FAIL,"该群聊已被您创建,请换个名称");
        }
        String iconUrl = createGroupDTO.getIconUrl();

        if(Boolean.FALSE.equals(redisByteTemplate.hasKey(iconUrl))){
            return ResultWrapper.fail(ReturnEnum.UPLOAD_FAIL);
        }
        OssUtil.uploadImage(redisByteTemplate.opsForValue().get(iconUrl),iconUrl);
        GroupInfo groupInfo =GroupInfo.builder()
                .groupName(groupName)
                .groupIcon(createGroupDTO.getIconUrl())
                .ownerId(id)
                .createTime(LocalDateTime.now())
                .number(1)
                .build();
        groupInfoService.save(groupInfo);
        Integer groupId=groupInfoService.query().eq("owner_id",id).eq("group_name",groupName).one().getId();
        GroupMember groupMember =GroupMember.builder()
                .groupId(groupId)
                .memberId(id)
                .joinTime(LocalDateTime.now())
                .nickName(createGroupDTO.getNickname())
                .status(1)
                .build();
        groupMemberService.save(groupMember);
        return ResultWrapper.success(ReturnEnum.SUCCESS,"创建成功");
    }
    /**
     * 显示个人添加的所有群聊
     * @return GroupListContactVO
     */
    @GetMapping("show-all")
    public ResultWrapper<List<GroupListContactVO>> showAll() {
        Integer id= StpUtil.getLoginIdAsInt();
        return ResultWrapper.success(ReturnEnum.SUCCESS,groupMemberService.getYourGroupList(id));
    }

    /**
     * 显示群聊成员
     * @param groupId 群聊id
     * @return PersonContactListVO
     */
    @GetMapping("show-members")
    public ResultWrapper<List<PersonContactListVO>> showMembers(@RequestParam Integer groupId) {
        return ResultWrapper.success(ReturnEnum.SUCCESS,groupMemberService.getGroupMemberList(groupId));
    }

    /**
     * 搜索群聊
     * @param groupName 群聊名称/群聊id
     * @return GroupInfo
     */
    @GetMapping("search")
    public ResultWrapper<List<GroupInfo>> search(@RequestParam String groupName) {
        String column=null;
        if(groupInfoService.query().eq("group_name",groupName).exists()){
            column="group_name";
        }else if(groupInfoService.query().eq("id",groupName).exists()){
            column="id";
        }
        if(column==null){
            return ResultWrapper.fail(ReturnEnum.USER_NOT_EXIST,null);
        }
       return ResultWrapper.success(ReturnEnum.SUCCESS,groupInfoService.query().eq(column,groupName).list());
    }

    /**
     * 申请加入群聊
        * @param addGroupDTO 申请加入群聊信息
     * @return String
     */
    @PostMapping("add")
    public ResultWrapper<String> add(@RequestBody AddGroupDTO addGroupDTO) {
        Integer id= StpUtil.getLoginIdAsInt();
        Integer groupId=addGroupDTO.getGroupId();
        if(!groupInfoService.query().eq("id",groupId).exists()){
            return ResultWrapper.fail(ReturnEnum.FAIL,"该群聊不存在");
        }
        if(groupMemberService.query().eq("group_id",groupId).eq("member_id",id).eq("status",1).exists()){
            return ResultWrapper.fail(ReturnEnum.SUCCESS,"您已经是群聊成员");
        }
        if(groupMemberService.query().eq("group_id",groupId).eq("member_id",id).eq("status",0).exists()){
            return ResultWrapper.fail(ReturnEnum.SUCCESS,"等待群主同意中");
        }
        GroupMember groupMember =GroupMember.builder()
                .groupId(groupId)
                .memberId(id)
                .joinTime(LocalDateTime.now())
                .status(0)
                .sayHello(addGroupDTO.getSayHello())
                .nickName(addGroupDTO.getNickname())
                .build();
        groupMemberService.save(groupMember);
        return ResultWrapper.success(ReturnEnum.SUCCESS,"已发送请求，请等待对方同意");
    }

    /**
     * 展示添加用户信息
     * @return WaitAddListVO
     */
    @GetMapping("show-add")
    public ResultWrapper<List<GroupWaitAddListVO>> showAdd() {
        Integer id= StpUtil.getLoginIdAsInt();
        return ResultWrapper.success(ReturnEnum.SUCCESS,groupMemberService.getWaitAddList(id));
    }

    /**
     * 同意加入群聊
     * @param groupId 群聊id
     * @param memberId 成员id
     * @return String
     */
    @GetMapping("accept")
    public ResultWrapper<String> accept(@RequestParam Integer groupId,@RequestParam Integer memberId) {
       groupMemberService.update(new UpdateWrapper<GroupMember>().eq("group_id",groupId).eq("member_id",memberId).set("status",1));
        groupInfoService.update(new UpdateWrapper<GroupInfo>().eq("id", groupId).setSql("number=number+1"));
        return ResultWrapper.success(ReturnEnum.SUCCESS,"已同意加入群聊");
    }

    /**
     * 群主拒绝成员加入群聊
     * @param groupId 群聊id
     * @param memberId 成员id
     * @return String
     */
    @GetMapping("refuse")
    public ResultWrapper<String> refuse(@RequestParam Integer groupId,@RequestParam Integer memberId) {
        groupMemberService.remove(new UpdateWrapper<GroupMember>().eq("group_id",groupId).eq("member_id",memberId));
        return ResultWrapper.success(ReturnEnum.SUCCESS,"已拒绝加入该群聊");
    }

    /**
     * 成员退出群聊
     * @param groupId 群聊id
     * @return String
     */
    @GetMapping("quit")
    public ResultWrapper<String> quit(@RequestParam Integer groupId) {
        Integer id= StpUtil.getLoginIdAsInt();
        if(groupInfoService.query().eq("id",groupId).eq("owner_id",id).exists()){
            return ResultWrapper.fail(ReturnEnum.FAIL,"你是群主，无法退出群聊");
        }
        groupMemberService.remove(new UpdateWrapper<GroupMember>().eq("group_id",groupId).eq("member_id",id));
        groupInfoService.update(new UpdateWrapper<GroupInfo>().eq("id", groupId).setSql("number=number-1"));
        return ResultWrapper.success(ReturnEnum.SUCCESS,"已退出该群聊");
    }
    /**
     * 群主删除成员
     * @param groupId 群聊id
     * @param memberId 成员id
     * @return String
     */
    @GetMapping("deleteUser")
    public ResultWrapper<String> deleteUser(@RequestParam Integer groupId,@RequestParam Integer memberId) {
        Integer id= StpUtil.getLoginIdAsInt();
        if(id.equals(memberId)){
            return ResultWrapper.fail(ReturnEnum.FAIL,"不能删除自己");
        }
        if(groupInfoService.query().eq("id",groupId).eq("owner_id",id).exists()){
            groupMemberService.remove(new UpdateWrapper<GroupMember>().eq("group_id",groupId).eq("member_id",memberId));
            groupInfoService.update(new UpdateWrapper<GroupInfo>().eq("id", groupId).setSql("number=number-1"));
            return ResultWrapper.success(ReturnEnum.SUCCESS,"已删除该成员");
        }
        return ResultWrapper.fail(ReturnEnum.FAIL,"你不是群主，无法删除成员");
    }
    /**
     * 群主解散群聊
     * @param groupId 群聊id
     * @return String
     */
    @GetMapping("deleteGroup")
    public ResultWrapper<String> deleteGroup(@RequestParam Integer groupId) {
        Integer id= StpUtil.getLoginIdAsInt();
        if(groupInfoService.query().eq("id",groupId).eq("owner_id",id).exists()){
            groupMemberService.remove(new UpdateWrapper<GroupMember>().eq("group_id",groupId));
            groupInfoService.removeById(groupId);
            return ResultWrapper.success(ReturnEnum.SUCCESS,"已解散该群聊");
        }
        return ResultWrapper.fail(ReturnEnum.FAIL,"你不是群主，无法解散群聊");
    }
    /**
     * 获取昵称
     * @param groupId 群聊id
     * @return String
     */
    @GetMapping("get-nickname")
    public  ResultWrapper<String> getNickname(@RequestParam Integer groupId) {
        Integer id = StpUtil.getLoginIdAsInt();
        GroupMember groupMember = groupMemberService.query()
                .eq("group_id", groupId)
                .eq("member_id", id)
                .one();
        return ResultWrapper.success(ReturnEnum.SUCCESS,groupMember.getNickName());
    }
    /**
     * 修改昵称
     * @param groupId 群聊id
     * @param nickname 昵称
     * @return String
     */
    @GetMapping("reset-nickname")
    public  ResultWrapper<String> resetNickname(@RequestParam Integer groupId,@RequestParam String nickname) {
        Integer id = StpUtil.getLoginIdAsInt();
        groupMemberService.update(Wrappers.<GroupMember>update()
                .eq("group_id",groupId).eq("member_id",id)
                .set("nick_name",nickname));
        return ResultWrapper.success(ReturnEnum.SUCCESS,"修改成功");
    }
    /**
     * 获取群聊人数
     * @param groupId 群聊id
     * @return Integer
     */
    @GetMapping("get-number")
    public  ResultWrapper<Integer> getNumber(@RequestParam Integer groupId) {
        return ResultWrapper.success(ReturnEnum.SUCCESS,groupInfoService.query().eq("id",groupId).one().getNumber());
    }
}
